import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Layout from "@/layout/index.vue";
import Login from "@/views/Login/index.vue";
import NProgress from "nprogress";
import { Permmenu, Person } from "@/api"
// import { authStore } from "@/store/authority";
// const { setMenus, setPerms, setUserinfo } = authStore()

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/layout",
    meta: {
      title: "首页"
    }
  },
  {
    path: "/layout",
    name: "layout",
    component: Layout,
    meta: {
      title: "主界面"
    },
    children: [
      {
        path: "/user",
        name: "user",
        component: () => import("@/views/sys/user/index.vue"),
        meta: {
          title: "用户列表"
        }
      },
      {
        path: "/menu",
        name: "menu",
        component: () => import("@/views/sys/menu/index.vue"),
        meta: {
          title: "菜单"
        }
      },
      {
        path: "/role",
        name: "role",
        component: () => import("@/views/sys/role/index.vue"),
        meta: {
          title: "角色列表"
        }
      },
      {
        path: "/dept",
        name: "dept",
        component: () => import("@/views/sys/config/index.vue"),
        meta: {
          title: "部门管理"
        }
      },
      {
        path: "/goods",
        name: "goods",
        component: () => import("@/views/shop/goods/index.vue"),
        meta: {
          title: "商品列表"
        }
      },
    ]
  },
  {
    path: "/login",
    name: "login",
    component: Login
  },
  // {
  //   path: "/about",
  //   name: "about",
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  // },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  //除了去登录,其他的地方,都要求有token
  if (to.path == "/login") {
    next();
  } else {
    if (localStorage.getItem("token") == null) {
      next("/login");
    }
  }
  next();
})
router.beforeResolve(async (to, from, next) => {
  //如果是从登录页面条件到 主页面,就需要获取 菜单和权限
  if (from.path == "/login" && to.path == "/layout") {
    if (from.path == "/login" && to.path == "/layout") {
      let res1 = await Permmenu()
      let { data: { data } } = res1
      localStorage.setItem("menus", JSON.stringify(data))
    }
  }
  next()
})
router.afterEach((to, from) => {
  NProgress.done()
});


export default router;
